package com.yonyougov.devops.cruxcisupport.file;

import com.yonyougov.devops.cruxcisupport.attachment.AttachmentEntity;
import com.yonyougov.devops.cruxcisupport.attachment.AttachmentService;
import com.yonyougov.devops.fwc.api.dto.BaseResponseDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags = "上传文件")
@RestController
@RequestMapping("/api/v2/file")
public class FileController {

    @Value("${upload.filepath}")
    private String filepath;

    @Autowired
    private AttachmentService attachmentService;

    //<!--用户自定义代码开始-->

    @ApiOperation(value = "前端上传附件调用", notes = "新增附件")
    @PostMapping(value = "/upload")
    @SneakyThrows
    public BaseResponseDto uploadFile(@RequestParam("files") MultipartFile[] files) {
        List<String> urls = Stream.of(files).map(f -> {
            File file = new File(filepath + File.separator +
                    DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-SS").format(LocalDateTime.now()));
            if (!file.exists()) {
                file.mkdirs();
            }
            File dest = new File(file, f.getOriginalFilename());
            try (InputStream in = f.getInputStream();
                 OutputStream os = new FileOutputStream(dest)) {
                int bytesRead;
                byte[] buffer = new byte[1024];
                while ((bytesRead = in.read(buffer, 0, 1024)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                return dest.getCanonicalPath();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        BaseResponseDto result = BaseResponseDto.getSuccessInstance();
        result.put("data", urls);
        return result;
    }

    @ApiOperation(value = "前端下载附件调用", notes = "下载附件")
    @GetMapping(value = "/download")
    @SneakyThrows
    public void downloadFile(@RequestParam(name = "file") BigInteger id, HttpServletResponse response) {
        response.setHeader("Context-Type", "application/octet-stream");
        AttachmentEntity attachmentEntity = attachmentService.get(id);
        File file = new File(attachmentEntity.getAttachmentUrl());
        if (!file.exists()) {
            return;
        }
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {
            //1.设置文件ContentType类型
            response.setContentType("application/octet-stream;charset=UTF-8");
            //2.转码
            String fileName = file.getName();
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            int b = 0;
            byte[] buffer = new byte[1024];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //<!--用户自定义代码结束-->
}
